<?php
/**
 * Created by xun at 2020/5/14
 */
namespace app\module\wechat;

use app\storage\Db;
use app\storage\WechatHelper;

class Notify extends \app\base\BaseObject
{

    public function sendTemplate($client, $to_openid) {
        $params = Db::getInstance()->getTemplateParams();
        if (!empty($params)) {
            $template_id = $params[0]['template_id'];
            $first = $params[0]['first_data'];
            $first_color = $params[0]['first_data_color'];
            // $last = $params[0]['data_remark'];
            // $url = $params[0]['jump_url'];
            // $url = "http://quanjian.xm0760.vip/home_wx/mingpian?mid={$to_openid}&from=singlemessage";
            $url = "http://quanjian.xm0760.vip/home_wx/mingpian";
            $remark = $params[0]['data_remark'];
            $remark_color = $params[0]['data_remark_color'];
            // template format
            $data = [
                'touser' => $to_openid,
                'template_id' => $template_id,
                'url' => $url,
                'data' => [
                    'first' => [
                        'value' => $first,
                        'color' => $first_color
                    ],
                    'keyword1' => [
                        'value' => $client['username'],
                        'color' => '#000000',
                    ],
                    'keyword2' => [
                        'value' => '',
                        'color' => '#000000',
                    ],
                    'keyword3' => [
                        'value' => date('Y-m-d H:i:s', time()),
                        'color' => '#000000',
                    ],
                    'remark' => [
                        'value' => $remark,
                        'color' => $remark_color,
                    ]
                ],
            ];
            $json = json_encode($data);
            // todo
            // foreach ($params as $param) {
            //     $data['data'][$params['parameter']] = $params[]
            // }
            $token = WechatHelper::getInstance()->getAccessToken();
            $url = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=' . $token;
            $ch = curl_init($url);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
            $output = curl_exec($ch);
            curl_close($ch);
            $json = json_decode($output, true);
            if ($json["errmsg"] == "ok") {
                //发送成功
            }
        }
    }
}